import { makeAutoObservable, runInAction } from 'mobx';
import { request } from '@/request';

type Params = {
    mdrender: boolean; // 当为 false 时，不渲染。默认为 true，渲染出现的所有 markdown 格式文本。
};

type TopicsTab = '' | 'ask' | 'share' | 'job' | 'good' | 'dev';

type Topic = {
    tab: TopicsTab;
    title: string;
    content: string;
    [key: string]: any;
};

const accesstoken = localStorage.getItem('accesstoken');

class TopicStore {
    mdrender: boolean = false;

    topic: Topic = {
        tab: '',
        title: '',
        content: '',
    };

    constructor() {
        makeAutoObservable(this);
    }

    // 主题详情
    async getTopic(
        id: string,
        params: Params = {
            mdrender: false,
        },
    ) {
        const res: any = await request.get(`/api/v1/topic/${id}`, { ...params, accesstoken });
        if (res.success && res.data) {
            this.topic = res.data;
        }
    }

    setTab(tab: TopicsTab) {
        this.topic.tab = tab;
    }

    setTitle(title: string) {
        this.topic.title = title;
    }

    setContent(content: string) {
        this.topic.content = content;
    }

    // 新建主题
    async postTopics() {
        const res: any = await request.post('/api/v1/topics', {
            tab: this.topic.tab,
            title: this.topic.title,
            content: this.topic.content,
        });
        const { success } = res;
        if (success) {
            // 新建成功
        }
    }

    // 编辑主题
    async postTopicsUpdate() {
        const res: any = await request.post('/api/v1/topic/update', {
            tab: this.topic.tab,
            title: this.topic.title,
            content: this.topic.content,
        });
        if (res.success) {
            return res;
        } else {
            return null;
        }
    }
}

export default TopicStore;
